<template>
  <div class="version-approval-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>审批列表</span>
          <el-button 
            type="text" 
            size="small" 
            @click="loadApprovals"
            :loading="loading"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="待审批" name="pending">
          <el-empty v-if="pendingApprovals.length === 0 && !loading" description="暂无待审批的申请" />
          <div v-else class="approval-list">
            <div
              v-for="approval in pendingApprovals"
              :key="approval.id"
              class="approval-item"
            >
              <div class="approval-header">
                <div class="approval-info">
                  <el-link 
                    type="primary" 
                    @click="handleViewVersion(approval.version_id)"
                  >
                    {{ approval.version_name || approval.version_id }}
                  </el-link>
                  <span class="status-change">
                    {{ getStatusName(approval.from_status) }} → {{ getStatusName(approval.to_status) }}
                  </span>
                </div>
                <el-tag type="warning">待审批</el-tag>
              </div>
              <div class="approval-body">
                <div v-if="approval.reason" class="approval-reason">
                  <span class="label">申请原因：</span>
                  <span>{{ approval.reason }}</span>
                </div>
                <div class="approval-meta">
                  <span>申请人：{{ getRequesterName(approval) }}</span>
                  <span>申请时间：{{ formatDateTime(approval.requested_at) }}</span>
                </div>
              </div>
              <div class="approval-actions">
                <el-button
                  type="success"
                  size="small"
                  @click="handleApprove(approval, true)"
                  :loading="approvingId === approval.id"
                >
                  通过
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleApprove(approval, false)"
                  :loading="approvingId === approval.id"
                >
                  拒绝
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="已审批" name="approved">
          <el-empty v-if="approvedApprovals.length === 0 && !loading" description="暂无已审批的记录" />
          <div v-else class="approval-list">
            <div
              v-for="approval in approvedApprovals"
              :key="approval.id"
              class="approval-item"
            >
              <div class="approval-header">
                <div class="approval-info">
                  <el-link 
                    type="primary" 
                    @click="handleViewVersion(approval.version_id)"
                  >
                    {{ approval.version_name || approval.version_id }}
                  </el-link>
                  <span class="status-change">
                    {{ getStatusName(approval.from_status) }} → {{ getStatusName(approval.to_status) }}
                  </span>
                </div>
                <el-tag :type="approval.status === 'approved' ? 'success' : 'danger'">
                  {{ approval.status === 'approved' ? '已通过' : '已拒绝' }}
                </el-tag>
              </div>
              <div class="approval-body">
                <div v-if="approval.reason" class="approval-reason">
                  <span class="label">申请原因：</span>
                  <span>{{ approval.reason }}</span>
                </div>
                <div class="approval-meta">
                  <span>申请人：{{ getRequesterName(approval) }}</span>
                  <span v-if="approval.approved_by">审批人：{{ getApproverName(approval) }}</span>
                  <span v-if="approval.approved_at">
                    审批时间：{{ formatDateTime(approval.approved_at) }}
                  </span>
                  <span v-if="approval.status === 'cancelled' && approval.approved_at">
                    取消时间：{{ formatDateTime(approval.approved_at) }}
                  </span>
                </div>
                <div v-if="approval.approval_notes" class="approval-notes">
                  <span class="label">审批意见：</span>
                  <span>{{ approval.approval_notes }}</span>
                </div>
                <div v-if="approval.rejection_reason" class="approval-rejection">
                  <span class="label">拒绝原因：</span>
                  <span>{{ approval.rejection_reason }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approvalDialogVisible"
      :title="approvalDialogTitle"
      width="500px"
    >
      <el-form :model="approvalForm" label-width="100px">
        <el-form-item label="审批意见">
          <el-input
            v-model="approvalForm.notes"
            type="textarea"
            :rows="4"
            placeholder="请输入审批意见"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approvalDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmApproval"
          :loading="submitting"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import versionAPI from '@/api/version'
import type { VersionTransitionApproval } from '@/types/version'
import { formatDateTime } from '@/utils/date'
import { useVersionStates } from '@/composables/useVersionStates'

interface Props {
  projectId?: string
  status?: string
}

const props = defineProps<Props>()
const { getStateByCode } = useVersionStates()

const router = useRouter()

const loading = ref(false)
const activeTab = ref('pending')
const pendingApprovals = ref<VersionTransitionApproval[]>([])
const approvedApprovals = ref<VersionTransitionApproval[]>([])
const approvalDialogVisible = ref(false)
const approvalForm = ref({
  notes: ''
})
const currentApproval = ref<VersionTransitionApproval | null>(null)
const approveAction = ref<boolean>(true)
const submitting = ref(false)
const approvingId = ref<string | null>(null)

const approvalDialogTitle = computed(() => {
  return approveAction.value ? '审批通过' : '审批拒绝'
})

// 加载审批列表
const loadApprovals = async () => {
  try {
    loading.value = true
    
    // 加载待审批列表
    const pendingResponse = await versionAPI.getPendingApprovals(props.projectId)
    pendingApprovals.value = pendingResponse.approvals || []
    
    // 加载已审批历史
    if (activeTab.value === 'approved') {
      await loadApprovedHistory()
    }
  } catch (error) {
    console.error('获取审批列表失败:', error)
    ElMessage.error('获取审批列表失败')
  } finally {
    loading.value = false
  }
}

// 加载已审批历史
const loadApprovedHistory = async () => {
  try {
    const response = await versionAPI.getApprovalHistory({
      projectId: props.projectId,
      status: props.status,
      limit: 50
    })
    approvedApprovals.value = response.approvals || []
  } catch (error) {
    console.error('获取审批历史失败:', error)
    ElMessage.error('获取审批历史失败')
  }
}

// 监听props变化
watch(() => [props.projectId, props.status], () => {
  if (activeTab.value === 'approved') {
    loadApprovedHistory()
  } else {
    loadApprovals()
  }
})

// 监听tab切换
watch(activeTab, (newTab) => {
  if (newTab === 'approved') {
    loadApprovedHistory()
  } else {
    loadApprovals()
  }
  // 通知父组件tab变化
  emit('tabChange', newTab)
})

// 处理审批
const handleApprove = (approval: VersionTransitionApproval, approved: boolean) => {
  currentApproval.value = approval
  approveAction.value = approved
  approvalForm.value.notes = ''
  approvalDialogVisible.value = true
}

// 确认审批
const confirmApproval = async () => {
  if (!currentApproval.value) return

  try {
    submitting.value = true
    approvingId.value = currentApproval.value.id

    await versionAPI.approveTransitionRequest(currentApproval.value.id, {
      approved: approveAction.value,
      notes: approvalForm.value.notes
    })

    ElMessage.success(approveAction.value ? '审批通过' : '审批已拒绝')
    approvalDialogVisible.value = false
    loadApprovals()
    emit('approved')
  } catch (error: any) {
    console.error('审批失败:', error)
    ElMessage.error(error.message || '审批失败')
  } finally {
    submitting.value = false
    approvingId.value = null
  }
}

// 查看版本
const handleViewVersion = (versionId: string) => {
  router.push(`/versions/${versionId}`)
}

const getStatusName = (status: string) => {
  // 优先使用状态管理中的名称
  const state = getStateByCode(status)
  if (state?.name) {
    return state.name
  }
  
  // 后备映射
  const nameMap: Record<string, string> = {
    draft: '草稿',
    planning: '规划中',
    development: '开发中',
    testing: '测试中',
    pre_release: '预发布',
    released: '已发布',
    deprecated: '已废弃',
    archived: '已归档'
  }
  return nameMap[status] || status
}

// 获取申请人名称
const getRequesterName = (approval: VersionTransitionApproval) => {
  if (approval.approvers && approval.approvers.length > 0) {
    const requester = approval.approvers.find(a => a.user_id === approval.requester_id)
    if (requester) {
      return requester.name || approval.requester_id
    }
  }
  return approval.requester_id
}

// 获取审批人名称
const getApproverName = (approval: VersionTransitionApproval) => {
  if (approval.approved_by && approval.approvers && approval.approvers.length > 0) {
    const approver = approval.approvers.find(a => a.user_id === approval.approved_by)
    if (approver) {
      return approver.name || approval.approved_by
    }
  }
  return approval.approved_by || ''
}

const emit = defineEmits<{
  approved: []
  tabChange: [tab: string]
}>()

// 暴露方法给父组件
defineExpose({
  loadApprovals
})

onMounted(() => {
  loadApprovals()
})
</script>

<style scoped lang="scss">
.version-approval-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .approval-list {
    .approval-item {
      padding: 16px;
      margin-bottom: 16px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      background: #fafafa;

      &:last-child {
        margin-bottom: 0;
      }

      .approval-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .approval-info {
          display: flex;
          align-items: center;
          gap: 12px;

          .status-change {
            color: #606266;
            font-size: 14px;
          }
        }
      }

      .approval-body {
        margin-bottom: 12px;

        .approval-reason,
        .approval-notes,
        .approval-rejection {
          margin-bottom: 8px;
          font-size: 14px;
          color: #606266;

          .label {
            font-weight: 500;
            color: #303133;
          }
        }

        .approval-meta {
          display: flex;
          gap: 16px;
          font-size: 13px;
          color: #909399;
          margin-top: 8px;
        }
      }

      .approval-actions {
        display: flex;
        gap: 8px;
        justify-content: flex-end;
      }
    }
  }
}
</style>

